<template>
  <div class="icon-selector">
    <!-- 触发按钮 -->
    <el-button @click="openDrawer" v-if="!inline">
      <el-icon v-if="modelValue"><component :is="modelValue" /></el-icon>
      <span v-if="modelValue">&nbsp;{{ modelValue }}</span>
      <span v-else>选择图标</span>
    </el-button>

    <!-- 内联模式 -->
    <div v-else class="inline-mode">
      <!-- 分类标签页 -->
      <el-tabs v-model="activeCategory" class="mb-4" type="card">
        <el-tab-pane
          v-for="category in iconCategories"
          :key="category.key"
          :label="category.name"
          :name="category.key"
        />
      </el-tabs>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索图标..."
        prefix-icon="Search"
        class="mb-4"
      />
      <div class="icon-grid">
        <div
          v-for="icon in filteredIcons"
          :key="icon"
          class="icon-item"
          :class="{ active: modelValue === icon }"
          @click="selectIcon(icon)"
        >
          <el-icon class="icon"><component :is="icon" /></el-icon>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
    </div>

    <!-- 抽屉面板 -->
    <el-drawer
      v-model="drawerVisible"
      title="选择图标"
      size="85%"
      :before-close="handleClose"
      class="icon-selector-drawer"
    >
      <!-- 分类标签页 -->
      <el-tabs v-model="activeCategory" class="mb-4" type="card">
        <el-tab-pane
          v-for="category in iconCategories"
          :key="category.key"
          :label="category.name"
          :name="category.key"
        />
      </el-tabs>

      <!-- 搜索框 -->
      <el-input
        v-model="searchKeyword"
        placeholder="搜索图标..."
        prefix-icon="Search"
        class="mb-4"
      />

      <!-- 图标网格 -->
      <div class="icon-grid">
        <div
          v-for="icon in filteredIcons"
          :key="icon"
          class="icon-item"
          :class="{ active: modelValue === icon }"
          @click="selectIcon(icon)"
        >
          <el-icon class="icon"><component :is="icon" /></el-icon>
          <span class="icon-name">{{ icon }}</span>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import type { IconSelectorProps } from './types'
  import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  import { iconCategories, assignUncategorizedIcons } from './icon-categories'

  // 定义props
  const props = withDefaults(defineProps<IconSelectorProps>(), {
    modelValue: '',
    inline: false
  })

  // 定义emits
  const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void
    (e: 'change', value: string): void
  }>()

  // 状态管理
  const drawerVisible = ref(false)
  const searchKeyword = ref('')
  const selectedIcon = ref(props.modelValue)
  const activeCategory = ref('all')

  // 获取所有图标名称
  const allIcons = ref<string[]>(Object.keys(ElementPlusIconsVue))

  // 处理图标分类
  const categorizedIcons = ref(assignUncategorizedIcons(allIcons.value))

  // 过滤图标（同时考虑分类和搜索关键词）
  const filteredIcons = computed(() => {
    // 获取当前分类的图标
    const category = categorizedIcons.value.find(
      (cat: Record<string, any>) => cat.key === activeCategory.value
    )
    const categoryIcons = category?.icons || []

    // 应用搜索过滤
    if (!searchKeyword.value) return categoryIcons
    return categoryIcons.filter((icon: string) =>
      icon.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  })

  // 监听外部值变化
  watch(
    () => props.modelValue,
    (newValue: string) => {
      selectedIcon.value = newValue
    }
  )

  // 打开抽屉
  const openDrawer = () => {
    drawerVisible.value = true
  }

  // 关闭抽屉
  const handleClose = () => {
    drawerVisible.value = false
  }

  // 选择图标
  const selectIcon = (icon: string) => {
    selectedIcon.value = icon
    emit('update:modelValue', icon)
    emit('change', icon)
    if (!props.inline) {
      handleClose()
    }
  }
</script>

<style scoped lang="scss">
  .icon-selector-drawer {
    --el-drawer-padding-primary: 24px;
  }

  .icon-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 20px;
    max-height: calc(100vh - 220px);
    overflow-y: auto;
    padding: 10px;
  }

  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

    &:hover {
      background-color: var(--el-bg-color-hover);
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    &.active {
      background-color: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
      border: 2px solid var(--el-color-primary);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }
  }

  .icon {
    font-size: 28px;
    margin-bottom: 12px;
    color: var(--el-text-color-primary);
  }

  .icon-name {
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
    text-align: center;
    color: var(--el-text-color-secondary);
  }

  .inline-mode {
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    padding: 16px;
  }
</style>
